//
//  Download.m
//  Example13-2
//
//  Created by 孙晓晔 on 2017/4/25.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "Download.h"
#import <UIKit/UIKit.h>
#import "DownloadOperation.h"

@interface Download()<DownloadOperationDelegate>

@end

@implementation Download

-(instancetype)initWithUrl:(NSArray*)arr {
    self = [super init];
    
    if (self) {
        _dict = [NSMutableDictionary dictionary];
        _urlArr = arr;
    }
    
    return self;
}

-(void)start:(NSInteger)count {
    
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    queue.maxConcurrentOperationCount = count;
    
    for (NSString *str in self.urlArr) {
        NSLog(@"%@", str);
        
        DownloadOperation *op1 = [[DownloadOperation alloc]initWithUrl:str];
        op1.delegate = self;
        
        
        [queue addOperation:op1];
    }
    
}

-(void)didFinishDownloadImage:(NSString*)strURL image:(UIImage *)image {
//    NSLog(@"下载文件 = %@", strURL);
    
    @synchronized (self) {
        [self.dict setValue:image forKey:strURL];
        
        if ([_dict count] == [_urlArr count]) {
            if ([self.delegate respondsToSelector:@selector(didFinishDownload:)]) {
                [self.delegate didFinishDownload:_dict];
            }
        }
    }
    
}

@end
